//
//  FileManager.swift
//  aquariumstudio
//
//  Created by zj on 2022/10/28.
//  Copyright © 2022 LXF. All rights reserved.
//

import Then
import UIKit

public extension String{
    func toUrlByCache()->URL?{
        return XXFileManager.shared.urlByCacheDir(cachePath: self)
    }
}

public class XXFileManager: NSObject {
    public static let shared = XXFileManager.init()
    
    public let fileManager = FileManager.default
    private override init() {
        home = NSHomeDirectory().toUrl
        document = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
        cache = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0]
        temp = NSTemporaryDirectory().toUrl
    }
    
    public let home:URL?
    public let document:URL?
    public let cache:URL?
    public let temp:URL?
    
    // 保存成为临时文件   返回一个 读取资源的url
    public func saveFileToTemp()->URL?{
        return nil
    }
    
    
    
    public func moveFile(_ url:URL,to tourl:URL)->Bool{
        if ifExistsRemove(tourl) {
            do {
//                try fileManager.moveItem(at: url, to: tourl)
                try fileManager.moveItem(atPath: url.xx_path(), toPath: tourl.xx_path())
            } catch  {
                XXLoger.e(error.localizedDescription)
                return false
            }
            
        }
        return true
    }
    public func ifExistsRemove(_ url:URL)->Bool{
            if fileExists(url: url) {
                do {
                    try fileManager.removeItem(atPath: url.xx_path())
                } catch  {
                    XXLoger.e(error.localizedDescription)
                    return false
                }
            }
        return true
    }
    public func removeAndCreateNewFile(_ url:URL)->Bool{
        if fileExists(url: url) {
            do {
                try fileManager.removeItem(atPath: url.xx_path())
                return fileManager.createFile(atPath: url.xx_path(), contents: nil)
            } catch  {
                XXLoger.e(error.localizedDescription)
                return false
            }
        }
        return fileManager.createFile(atPath: url.xx_path(), contents: nil)
    }
    public func fileExists(url:URL)->Bool{
        return fileManager.fileExists(atPath: url.xx_path())
    }
    
    public func urlByCacheDir(cachePath:String)->URL?{
        guard var url = cache else {
            XXLoger.e("cache == nil")
            return nil
        }
//        url = url.appendingPathComponent(dir)
//        if #available(iOS 16.0, *) {
//            url.append(path: cachePath)
//        } else {
        var cachePath = cachePath
        url = url.appendingPathComponent(cachePath.xx_trimPrefix(str: "/"))
//        }
        return url
    }
    
    // 保存成为缓存文件 返回一个生成的 读取资源的 指定名称, 指定名称会覆盖旧文件
    public func saveFileToCache(fileURL:URL,toDir dir:String = "app_cache",filename:String? = nil,ext:String? = nil)->String?{
        guard var url = cache else {
            XXLoger.e("cache == nil")
            return nil
        }
        
        url = url.appendingPathComponent(dir, isDirectory: true)
    
        if fileManager.fileExists(atPath: url.path) == false{
            do {
                try fileManager.createDirectory(at: url, withIntermediateDirectories: true)
            } catch  {
                XXLoger.e(error)
                return nil
            }
        }
        
        var _filename:String!
        
        if let filename = filename {
            _filename = filename
        }else{
//            _filename = UUID.init().uuidString
            _filename = fileURL.lastPathComponent.split(separator: ".").first?.description ?? UUID.init().uuidString
        }
        
        url = url.appendingPathComponent(_filename)
        
        var _ext:String!
        if let ext = ext {
            _ext = ext
        }else{
            _ext = fileURL.pathExtension
        }
        
        url = url.appendingPathExtension(_ext)
        
        do {
            if fileExists(url: url) {
                try fileManager.removeItem(at: url)
            }
            try fileManager.copyItem(at: fileURL, to: url)
        } catch {
            XXLoger.e(error.localizedDescription)
            return nil
        }
        
        return url.path.asNSString.replacingOccurrences(of: cache?.path ?? "", with: "")
    }
    
    // 保存成为缓存文件  返回一个生成的 读取资源的url  or 指定名称, 指定名称会覆盖旧文件  (弃用!!!!)
    public func saveFileToCache(data:Data,dir:String = "app_cache",filename:String? = nil,ext:String = "tmp")->URL?{
        guard var url = cache else {
            XXLoger.e("cache == nil")
            return nil }
        
        url = url.appendingPathComponent(dir, isDirectory: true)
        
        if fileManager.fileExists(atPath: url.absoluteString) == false{
            do {
                try fileManager.createDirectory(at: url, withIntermediateDirectories: true)
            } catch  {
                XXLoger.e(error)
                return nil
            }
        }
        
        var _filename:String!
        
        if let filename = filename {
            _filename = filename
        }else{
            _filename = UUID.init().uuidString
        }
        
        url = url.appendingPathComponent(_filename)
        
        url = url.appendingPathExtension(ext)
        
        do {
            try data.write(to: url)
        } catch {
            XXLoger.e(error)
            return nil
        }
         
        return url
    }
    
    public func saveFileToCache(filename:String? = nil,image:UIImage)->URL?{
        guard let data = image.pngData()else{
            XXLoger.e("to data error")
            return nil
        }
        return saveFileToCache(data:data,filename: filename,ext: "png")
    }
}
